package app1.rapidsquare.com.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.entity.StringEntity;
import app1.rapidsquare.com.activity.R;
import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.core.ConnectionDetector;

/**
 * Created by Hikmat on 07.08.2014.
 */

public abstract class AgileActivity extends ActionBarActivity {

    private TextView mTextViewCode;
    protected ImageView mImageViewLogo, mImageViewMenu;
    private ConnectionDetector mConnectionDetector;
    private Utility.RequestMethodType mRequestMethodType;
    private volatile String mUrl;
    protected StringEntity mHttpEntity;
    protected ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mConnectionDetector = new ConnectionDetector(this);
        LoadActionBar();
        mProgressDialog = new ProgressDialog(AgileActivity.this);
        mProgressDialog.setMessage("Please wait");
    }


    @Override
    protected void onPostResume() {
        super.onPostResume();

    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(
                mConnectionDetector,
                new IntentFilter(
                        android.net.ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mConnectionDetector);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    protected void LoadActionBar() {
        ActionBar mActionBar = getSupportActionBar();
        if (mActionBar != null) {
            mActionBar.setDisplayShowHomeEnabled(false);
            mActionBar.setHomeButtonEnabled(false);
            mActionBar.setDisplayShowTitleEnabled(false);
            LayoutInflater mInflater = LayoutInflater.from(this);

            View mCustomView = mInflater.inflate(R.layout.action_bar, null);

            mTextViewCode = (TextView) mCustomView
                    .findViewById(R.id.action_bar_title);
            mImageViewLogo = (ImageView) mCustomView.findViewById(R.id.action_bar_logo);

            mImageViewMenu = (ImageView) mCustomView.findViewById(R.id.imageViewMenu);

            mActionBar.setCustomView(mCustomView);
            mActionBar.setDisplayShowCustomEnabled(true);
            mTextViewCode.setText("");
        }
    }

    protected View.OnClickListener ConnectDialogOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ShowConnectDialog();
        }
    };

    protected void setTitle(String title) {
        mTextViewCode.setText(title);
    }

    protected void HideKeyboard() {
        if (getCurrentFocus() != null) {
            IBinder binder = getCurrentFocus().getWindowToken();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(binder, 0);
        }

    }

    private void ShowConnectDialog() {
        AlertDialog.Builder alertDialog;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            alertDialog = new AlertDialog.Builder(AgileActivity.this, AlertDialog.THEME_HOLO_LIGHT);
        else
            alertDialog = new AlertDialog.Builder(AgileActivity.this);

        View view = getLayoutInflater().inflate(R.layout.dialog_connect, null, false);
        final EditText editText = (EditText) view.findViewById(R.id.editTextSearchId);
        alertDialog.setView(view);
        alertDialog.setTitle(getResources().getString(R.string.alert_dialog_connect_title));
        alertDialog.setNegativeButton(R.string.cancel, null);
        alertDialog.setPositiveButton(R.string.connect, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (editText.getText().toString().trim().length() != 4) {
                    Toast.makeText(AgileActivity.this, getString(R.string.connect_is_not_valid), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!editText.getText().toString().equals(Utility.getUserSession(getApplicationContext()).Code)) {
                    SendConnect(editText.getText().toString());
                    Toast.makeText(AgileActivity.this, getString(R.string.connection_was_sent), Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(AgileActivity.this, getString(R.string.connect_cannot_add_yourself), Toast.LENGTH_SHORT).show();
            }
        });
        alertDialog.show();
    }

    private void SendConnect(final String code) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Utility.ConnectServer(Utility.SEND_NOTIFICATION_URL + "?userToken="
                        + Utility.getUserSession(AgileActivity.this).UserToken + "&code="
                        + code.trim(), Utility.RequestMethodType.GET, null);
            }
        }).start();
    }

    protected boolean IsAuthentication() {
        return Utility.getUserSession(getApplicationContext()) != null
                && !Utility.isNullOrEmpty(Utility.getUserSession(getApplicationContext()).UserToken);
    }

    protected boolean IsAvailableInternet() {
        return mConnectionDetector.getConnectingStatus();
    }

    protected void setUrl(String mUrl) {
        this.mUrl = mUrl;
    }

    public String getUrl() {
        return this.mUrl;
    }

    public Utility.RequestMethodType getRequestMethodType() {
        return mRequestMethodType;
    }

    public void setRequestMethodType(Utility.RequestMethodType mRequestMethodType) {
        this.mRequestMethodType = mRequestMethodType;
    }

    protected synchronized void SendRequest(boolean showDialog) {

        if (IsAvailableInternet()) {
            if (showDialog)
                mProgressDialog.show();
            new AsyncTask<Void, Void, String>() {

                @Override
                protected String doInBackground(Void... params) {
                    return Utility.ConnectServer(getUrl(), getRequestMethodType(), mHttpEntity);
                }

                @Override
                protected void onPostExecute(String result) {
                    getResponce(result);
                    if (mProgressDialog != null)
                        mProgressDialog.dismiss();
                }
            }.execute();
        }
    }

    protected abstract void getResponce(String result);
}


